#!/bin/sh
################################################################################
#      This file is part of OpenELEC - http://www.openelec.tv
#      Copyright (C) 2009-2016 Stephan Raue (stephan@openelec.tv)
#
#  OpenELEC is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 2 of the License, or
#  (at your option) any later version.
#
#  OpenELEC is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with OpenELEC.  If not, see <http://www.gnu.org/licenses/>.
################################################################################

if [ -z "$1" ]; then
  echo "Usage: $0 <branch-name>"
  exit 0
fi

PKG_NAME="kodi"
PKG_VERSION=""
BRANCH="$1"
GIT_REPO="git://github.com/xbmc/xbmc.git"
DEST_DIR="$PKG_NAME-$BRANCH"

echo "getting sources..."
  if [ ! -d $DEST_DIR.git ]; then
    git clone --depth 1 $GIT_REPO -b $BRANCH $DEST_DIR.git
  fi

  cd $DEST_DIR.git
  git pull

echo "getting version..."
  GIT_HASH=`git log -n1 --format=%h`
  VERSION_MAJOR=$(grep ^VERSION_MAJOR version.txt | cut -d" " -f2)
  VERSION_MINOR=$(grep ^VERSION_MINOR version.txt | cut -d" " -f2)
  VERSION_TAG=$(grep ^VERSION_TAG version.txt | cut -d" " -f2 | tr A-Z a-z)
  PKG_VERSION="$VERSION_MAJOR.$VERSION_MINOR-$VERSION_TAG-$GIT_HASH"
  # hack: empty version tag on release builds:
  if [ "$VERSION_TAG" = "version_tag" ] ; then
    PKG_VERSION="$VERSION_MAJOR.$VERSION_MINOR-$GIT_HASH"
  fi
  echo $PKG_VERSION
  cd ..

echo "copying sources..."
  rm -rf $PKG_NAME-$PKG_VERSION
  cp -R $DEST_DIR.git $PKG_NAME-$PKG_VERSION
  echo "$GIT_HASH" > $PKG_NAME-$PKG_VERSION/VERSION

echo "cleaning sources..."
  rm -rf $PKG_NAME-$PKG_VERSION/.git

echo "seperating theme..."
  rm -rf $PKG_NAME-theme-Confluence-$PKG_VERSION
  mv $PKG_NAME-$PKG_VERSION/addons/skin.confluence $PKG_NAME-theme-Confluence-$PKG_VERSION

echo "packing sources..."
  tar cvJf $PKG_NAME-$PKG_VERSION.tar.xz $PKG_NAME-$PKG_VERSION
  tar cvJf $PKG_NAME-theme-Confluence-$PKG_VERSION.tar.xz $PKG_NAME-theme-Confluence-$PKG_VERSION

echo "remove temporary sourcedir..."
  rm -rf $PKG_NAME-$PKG_VERSION
  rm -rf $PKG_NAME-theme-Confluence-$PKG_VERSION
